package com.cucn.vod.service.impl;

import com.aliyun.vod.upload.impl.UploadVideoImpl;
import com.aliyun.vod.upload.req.UploadStreamRequest;
import com.aliyun.vod.upload.resp.UploadStreamResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.vod.model.v20170321.DeleteVideoRequest;
import com.aliyuncs.vod.model.v20170321.DeleteVideoResponse;
import com.cucn.commonutils.Result;
import com.cucn.servicebase.exceptionhandler.GuliException;
import com.cucn.vod.service.VodService;
import com.cucn.vod.utils.ConstantVodUtils;
import com.cucn.vod.utils.InitVodClient;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Objects;

/**
 * @author KouChaoJie
 * @since: 2021/10/2 23:19
 */
@Service
public class VodServiceImpl implements VodService {
    /**
     * @param file 要上传的视频文件
     * @return 视频id
     */
    @Override
    public String uploadVideoAly(MultipartFile file) {
        try {

            //fileName:上传文件原始名称
            String fileName = file.getOriginalFilename();
            //title:上传后显示的名称
            String title = Objects.requireNonNull(fileName).substring(0, fileName.lastIndexOf("."));
            //InputStream:上传文件输入流
            InputStream inputStream = file.getInputStream();
            UploadStreamRequest request = new UploadStreamRequest(ConstantVodUtils.ACCESS_KEY_ID, ConstantVodUtils.ACCESS_KEY_SECRET, title, fileName, inputStream);

            UploadVideoImpl uploader = new UploadVideoImpl();
            UploadStreamResponse response = uploader.uploadStream(request);
            //请求视频点播服务的请求ID
            String videoId;
            videoId = response.getVideoId();
            return videoId;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 批量删除视频
     *
     * @param videoIdList 视频id集合
     */
    @Override
    public void removeMoreAlyVideo(List<String> videoIdList) {
        try {
            //初始化对象
            DefaultAcsClient client = InitVodClient.initVodClient(ConstantVodUtils.ACCESS_KEY_ID, ConstantVodUtils.ACCESS_KEY_SECRET);
            DeleteVideoRequest request = new DeleteVideoRequest();

            //videoIdList值进行转换
            String join = StringUtils.join(videoIdList.toArray(), ",");

            request.setVideoIds(join);

            client.getAcsResponse(request);
        } catch (Exception e) {
            e.printStackTrace();
            throw new GuliException(20001, "删除视频失败");
        }
    }
}
